#import "CustomTranslationView.h"

extern NSDictionary *translationDict;
extern NSString *findTranslationFor(NSString *text);
extern void refreshLocalizationInView(UIView *view);

extern BOOL disableTranslation;

@implementation CustomTranslationView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupUI];
    }
    return self;
}

- (void)setupUI {
    CGFloat contentHeight = 290;

    self.backgroundView = [[UIView alloc] initWithFrame:self.bounds];
    self.backgroundView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.6];
    self.backgroundView.alpha = 0;
    [self addSubview:self.backgroundView];
    
    self.contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width * 0.8, contentHeight)];
    self.contentView.center = self.center;
    self.contentView.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1.0];
    self.contentView.layer.cornerRadius = 16;
    self.contentView.layer.shadowColor = [UIColor blackColor].CGColor;
    self.contentView.layer.shadowOffset = CGSizeMake(0, 5);
    self.contentView.layer.shadowOpacity = 0.3;
    self.contentView.layer.shadowRadius = 10;
    self.contentView.alpha = 0;
    self.contentView.transform = CGAffineTransformMakeScale(0.8, 0.8);
    [self addSubview:self.contentView];
    
    // 标题
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, self.contentView.bounds.size.width - 40, 30)];
    titleLabel.text = @"添加自定义翻译";
    titleLabel.font = [UIFont boldSystemFontOfSize:20];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = [UIColor darkTextColor];
    [self.contentView addSubview:titleLabel];
    
    // 原始文本输入框
    self.originalTextField = [[UITextField alloc] initWithFrame:CGRectMake(20, 70, self.contentView.bounds.size.width - 40, 40)];
    self.originalTextField.placeholder = @"原文 (英文)";
    self.originalTextField.borderStyle = UITextBorderStyleRoundedRect;
    self.originalTextField.backgroundColor = [UIColor whiteColor];
    self.originalTextField.delegate = self;
    [self.contentView addSubview:self.originalTextField];
    
    // 翻译文本输入框
    self.translationTextField = [[UITextField alloc] initWithFrame:CGRectMake(20, 120, self.contentView.bounds.size.width - 40, 40)];
    self.translationTextField.placeholder = @"译文 (中文)";
    self.translationTextField.borderStyle = UITextBorderStyleRoundedRect;
    self.translationTextField.backgroundColor = [UIColor whiteColor];
    self.translationTextField.delegate = self;
    [self.contentView addSubview:self.translationTextField];
    
    UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, 44)];
    UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(doneButtonTapped)];
    toolbar.items = @[flexSpace, doneButton];
    self.translationTextField.inputAccessoryView = toolbar;
    
    UIView *buttonContainer = [[UIView alloc] initWithFrame:CGRectMake(20, 180, self.contentView.bounds.size.width - 40, 40)];
    [self.contentView addSubview:buttonContainer];
    
    // 保存按钮
    self.saveButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.saveButton.frame = CGRectMake(0, 0, buttonContainer.bounds.size.width/2 - 5, 40);
    [self.saveButton setTitle:@"保存" forState:UIControlStateNormal];
    [self.saveButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.saveButton.backgroundColor = [UIColor colorWithRed:0.0 green:0.48 blue:1.0 alpha:1.0];
    self.saveButton.layer.cornerRadius = 8;
    [self.saveButton addTarget:self action:@selector(saveTranslation) forControlEvents:UIControlEventTouchUpInside];
    [buttonContainer addSubview:self.saveButton];
    
    // 取消按钮
    self.cancelButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.cancelButton.frame = CGRectMake(buttonContainer.bounds.size.width/2 + 5, 0, buttonContainer.bounds.size.width/2 - 5, 40);
    [self.cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [self.cancelButton setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    self.cancelButton.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1.0];
    self.cancelButton.layer.cornerRadius = 8;
    [self.cancelButton addTarget:self action:@selector(hide) forControlEvents:UIControlEventTouchUpInside];
    [buttonContainer addSubview:self.cancelButton];
    
    // 管理词汇按钮
    UIButton *managerButton = [UIButton buttonWithType:UIButtonTypeSystem];
    managerButton.frame = CGRectMake(20, 230, self.contentView.bounds.size.width - 40, 40);
    [managerButton setTitle:@"管理汉化词汇" forState:UIControlStateNormal];
    // 增加按钮内边距 - 扩大点击区域
    managerButton.contentEdgeInsets = UIEdgeInsetsMake(10, 0, 10, 0);
    
    [managerButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    managerButton.backgroundColor = [UIColor colorWithRed:0.3 green:0.6 blue:0.9 alpha:1.0];
    managerButton.layer.cornerRadius = 8;
    managerButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    
    managerButton.layer.shadowColor = [UIColor blackColor].CGColor;
    managerButton.layer.shadowOffset = CGSizeMake(0, 2);
    managerButton.layer.shadowOpacity = 0.3;
    managerButton.layer.shadowRadius = 2;
    
    [managerButton addTarget:self action:@selector(showManager) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:managerButton];
    
   // 关闭按钮
    UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeSystem];
    closeButton.frame = CGRectMake(self.contentView.bounds.size.width - 50, 15, 40, 40); // 扩大点击区域
    [closeButton setTitle:@"×" forState:UIControlStateNormal];
    [closeButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    closeButton.titleLabel.font = [UIFont systemFontOfSize:30]; // 增大字号
    [closeButton addTarget:self action:@selector(hide) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:closeButton];

    CGFloat maxY = CGRectGetMaxY(managerButton.frame);
    if (maxY > contentHeight) {
        CGRect frame = self.contentView.frame;
        frame.size.height = maxY + 20;
        self.contentView.frame = frame;
        self.contentView.center = self.center;
    }
}

- (void)doneButtonTapped {
    [self.translationTextField resignFirstResponder];
}

- (void)show {
    self.originalTextField.text = @"";
    self.translationTextField.text = @"";
    
    [UIView animateWithDuration:0.3 animations:^{
        self.backgroundView.alpha = 1;
        self.contentView.alpha = 1;
        self.contentView.transform = CGAffineTransformIdentity;
    }];
    
    [self.originalTextField becomeFirstResponder];
}

- (void)hide {
    [UIView animateWithDuration:0.3 animations:^{
        self.backgroundView.alpha = 0;
        self.contentView.alpha = 0;
        self.contentView.transform = CGAffineTransformMakeScale(0.8, 0.8);
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

- (void)saveTranslation {
    NSString *original = self.originalTextField.text;
    NSString *translation = self.translationTextField.text;
    
    if (original.length > 0 && translation.length > 0) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSMutableDictionary *customDict = [[defaults dictionaryForKey:@"CustomTranslations"] mutableCopy];
        if (!customDict) {
            customDict = [NSMutableDictionary dictionary];
        }
        customDict[original] = translation;
        [defaults setObject:customDict forKey:@"CustomTranslations"];
        [defaults synchronize];
        
        NSMutableDictionary *newDict = [translationDict mutableCopy];
        newDict[original] = translation;
        translationDict = [newDict copy];
        
        UIWindow *keyWindow = [self findKeyWindow];
        if (keyWindow) {
            refreshLocalizationInView(keyWindow);
        }
        
        [self showSuccessMessage:@"保存成功！"];
        
        self.originalTextField.text = @"";
        self.translationTextField.text = @"";
        [self.originalTextField becomeFirstResponder];
    } else {
        [self showErrorMessage:@"请填写完整！"];
    }
}

- (void)showSuccessMessage:(NSString *)message {
    UILabel *messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 180, 40)];
    messageLabel.center = CGPointMake(self.contentView.bounds.size.width/2, self.contentView.bounds.size.height + 30);
    messageLabel.text = message;
    messageLabel.textColor = [UIColor whiteColor];
    messageLabel.backgroundColor = [UIColor colorWithRed:0.2 green:0.8 blue:0.2 alpha:0.9];
    messageLabel.textAlignment = NSTextAlignmentCenter;
    messageLabel.layer.cornerRadius = 8;
    messageLabel.clipsToBounds = YES;
    messageLabel.alpha = 0;
    [self.contentView addSubview:messageLabel];
    
    [UIView animateWithDuration:0.3 animations:^{
        messageLabel.alpha = 1;
    } completion:^(BOOL finished) {
        dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC));
        dispatch_after(delay, dispatch_get_main_queue(), ^{
            [UIView animateWithDuration:0.3 animations:^{
                messageLabel.alpha = 0;
            } completion:^(BOOL finished) {
                [messageLabel removeFromSuperview];
            }];
        });
    }];
}

- (void)showErrorMessage:(NSString *)message {
    UILabel *messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 120, 40)];
    messageLabel.center = CGPointMake(self.contentView.bounds.size.width/2, -40);
    messageLabel.text = message;
    messageLabel.textColor = [UIColor whiteColor];
    messageLabel.backgroundColor = [UIColor colorWithRed:1.0 green:0.2 blue:0.2 alpha:0.9];
    messageLabel.textAlignment = NSTextAlignmentCenter;
    messageLabel.layer.cornerRadius = 8;
    messageLabel.clipsToBounds = YES;
    messageLabel.alpha = 0;
    [self.contentView addSubview:messageLabel];
    
    [UIView animateWithDuration:0.3 animations:^{
        messageLabel.center = CGPointMake(self.contentView.bounds.size.width/2, -10);
        messageLabel.alpha = 1;
    } completion:^(BOOL finished) {
        dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC));
        dispatch_after(delay, dispatch_get_main_queue(), ^{
            [UIView animateWithDuration:0.3 animations:^{
                messageLabel.alpha = 0;
            } completion:^(BOOL finished) {
                [messageLabel removeFromSuperview];
            }];
        });
    }];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == self.originalTextField) {
        [self.translationTextField becomeFirstResponder];
    } else {
        [self saveTranslation];
    }
    return YES;
}

- (void)showManager {
    [self hide];
    
    TranslationManagerView *managerView = [[TranslationManagerView alloc] initWithFrame:self.superview.bounds];
    managerView.alpha = 0;
    [self.superview addSubview:managerView];
    
    [UIView animateWithDuration:0.3 animations:^{
        managerView.alpha = 1;
    }];
}

- (UIWindow *)findKeyWindow {
    UIWindow *keyWindow = nil;
    
    // iOS 13+ 兼容方法
    if (@available(iOS 13.0, *)) {
        for (UIScene *scene in [UIApplication sharedApplication].connectedScenes) {
            if (scene.activationState == UISceneActivationStateForegroundActive && 
                [scene isKindOfClass:[UIWindowScene class]]) {
                UIWindowScene *windowScene = (UIWindowScene *)scene;
                for (UIWindow *window in windowScene.windows) {
                    if (window.isKeyWindow) {
                        keyWindow = window;
                        break;
                    }
                }
                if (keyWindow) break;
            }
        }
    }
    
    if (!keyWindow) {
        NSArray *windows = [UIApplication sharedApplication].windows;
        for (UIWindow *window in windows) {
            if (window.windowLevel == UIWindowLevelNormal) {
                keyWindow = window;
                break;
            }
        }
    }
    
    if (!keyWindow) {
        keyWindow = [UIApplication sharedApplication].windows.firstObject;
    }
    
    return keyWindow;
}

@end

@implementation TranslationManagerView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        disableTranslation = YES;
        [self setupUI];
        [self loadTranslations];
    }
    return self;
}

- (void)close {
    [UIView animateWithDuration:0.3 animations:^{
        self.alpha = 0;
    } completion:^(BOOL finished) {
        disableTranslation = NO;
        [self removeFromSuperview];
    }];
}

- (void)loadTranslations {
NSDictionary *customDict = [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"CustomTranslations"];
    self.customTranslations = customDict ? [customDict mutableCopy] : [NSMutableDictionary dictionary];
    self.filteredTranslations = [self.customTranslations mutableCopy];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.isSearching ? 1 : 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.isSearching) {
        return self.filteredTranslations.count;
    }
    
    if (section == 0) {
        return translationDict.count - self.customTranslations.count;
    }
    return self.customTranslations.count;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    if (searchText.length == 0) {
        self.isSearching = NO;
        self.filteredTranslations = [self.customTranslations mutableCopy];
    } else {
        self.isSearching = YES;
        [self.filteredTranslations removeAllObjects];
        
        [self.customTranslations enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *value, BOOL *stop) {

            if ([key rangeOfString:searchText options:NSCaseInsensitiveSearch].location != NSNotFound ||
                [value rangeOfString:searchText options:NSCaseInsensitiveSearch].location != NSNotFound) {
                self.filteredTranslations[key] = value;
            }
        }];
    }
    
    [self.tableView reloadData];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    searchBar.text = @"";
    [searchBar resignFirstResponder];
    self.isSearching = NO;
    [self.tableView reloadData];
}

- (void)setupUI {
    self.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.7];

    // 内容视图
    CGFloat contentHeight = self.bounds.size.height - 80;
    UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(20, 50, self.bounds.size.width - 40, contentHeight)];
    contentView.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1.0];
    contentView.layer.cornerRadius = 16;
    contentView.clipsToBounds = YES;
    [self addSubview:contentView];
    
    // 标题
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, contentView.bounds.size.width, 40)];
    titleLabel.text = @"已保存词汇";
    titleLabel.font = [UIFont boldSystemFontOfSize:20];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = [UIColor darkTextColor];
    [contentView addSubview:titleLabel];
    
    // 搜索栏
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(10, 60, contentView.bounds.size.width - 20, 50)];
    searchBar.delegate = self;
    searchBar.placeholder = @"搜索词汇";
    searchBar.barTintColor = [UIColor clearColor];
    searchBar.backgroundImage = [[UIImage alloc] init];
    [contentView addSubview:searchBar];
    
    // 分割线
    UIView *divider = [[UIView alloc] initWithFrame:CGRectMake(20, 110, contentView.bounds.size.width - 40, 1)];
    divider.backgroundColor = [UIColor colorWithWhite:0.8 alpha:1.0];
    [contentView addSubview:divider];
    
    // 表格视图
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 111, contentView.bounds.size.width, contentView.bounds.size.height - 161) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    [contentView addSubview:self.tableView];
    
    // 按钮容器
    UIView *buttonContainer = [[UIView alloc] initWithFrame:CGRectMake(20, contentView.bounds.size.height - 50, contentView.bounds.size.width - 40, 40)];
    [contentView addSubview:buttonContainer];
    
    // 返回按钮
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    backButton.frame = CGRectMake(0, 0, (buttonContainer.bounds.size.width/2) - 5, 40);
    [backButton setTitle:@"返回" forState:UIControlStateNormal];
    [backButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    backButton.backgroundColor = [UIColor colorWithRed:0.3 green:0.6 blue:0.9 alpha:1.0];
    backButton.layer.cornerRadius = 8;
    [backButton addTarget:self action:@selector(backToAddView) forControlEvents:UIControlEventTouchUpInside];
    [buttonContainer addSubview:backButton];
    
    // 关闭按钮
    UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeSystem];
    closeButton.frame = CGRectMake((buttonContainer.bounds.size.width/2) + 5, 0, (buttonContainer.bounds.size.width/2) - 5, 40);
    [closeButton setTitle:@"关闭" forState:UIControlStateNormal];
    [closeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    closeButton.backgroundColor = [UIColor colorWithRed:0.0 green:0.48 blue:1.0 alpha:1.0];
    closeButton.layer.cornerRadius = 8;
    [closeButton addTarget:self action:@selector(close) forControlEvents:UIControlEventTouchUpInside];
    [buttonContainer addSubview:closeButton];
    self.tableView.sectionHeaderHeight = 30;
}

- (void)backToAddView {
    UIView *superview = self.superview;
    
    [UIView animateWithDuration:0.3 animations:^{
        self.alpha = 0;
    } completion:^(BOOL finished) {
        disableTranslation = NO;
        [self removeFromSuperview];
        
        CustomTranslationView *addView = [[CustomTranslationView alloc] initWithFrame:superview.bounds];
        [superview addSubview:addView];
        [addView show];
    }];
}

#pragma mark - Table View Data Source

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    NSString *title;
    
    if (self.isSearching) {
        title = @"搜索结果";
    } else {
        if (section == 0) {
            title = @"内置词汇";
        } else {
            title = @"自定义词汇";
        }
    }
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)];
    headerView.backgroundColor = [UIColor colorWithRed:0.92 green:0.92 blue:0.92 alpha:1.0];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 5, tableView.bounds.size.width - 30, 20)];
    titleLabel.text = title;
    titleLabel.font = [UIFont boldSystemFontOfSize:16];
    titleLabel.textColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:1.0];
    
    [headerView addSubview:titleLabel];
    
    UIView *bottomBorder = [[UIView alloc] initWithFrame:CGRectMake(0, 29.5, tableView.bounds.size.width, 0.5)];
    bottomBorder.backgroundColor = [UIColor colorWithWhite:0.8 alpha:1.0];
    [headerView addSubview:bottomBorder];
    
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"TranslationCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        // 调整字体大小
        cell.textLabel.font = [UIFont systemFontOfSize:16]; // 中文
        cell.detailTextLabel.font = [UIFont systemFontOfSize:14]; // 英文
        cell.detailTextLabel.textColor = [UIColor grayColor];
    }
    
    NSString *key = nil;
    NSString *value = nil;
    
    if (self.isSearching) {
        NSArray *filteredKeys = self.filteredTranslations.allKeys;
        if (indexPath.row < filteredKeys.count) {
            key = filteredKeys[indexPath.row];
            value = self.filteredTranslations[key];
        }
    } else {
        if (indexPath.section == 0) {
            NSArray *allKeys = translationDict.allKeys;
            NSMutableArray *builtInKeys = [NSMutableArray array];
            
            for (NSString *k in allKeys) {
                if (![self.customTranslations objectForKey:k]) {
                    [builtInKeys addObject:k];
                }
            }
            
            if (indexPath.row < builtInKeys.count) {
                key = builtInKeys[indexPath.row];
                value = translationDict[key];
            }
        } else {
            NSArray *customKeys = self.customTranslations.allKeys;
            if (indexPath.row < customKeys.count) {
                key = customKeys[indexPath.row];
                value = self.customTranslations[key];
            }
        }
    }
    
    if (key && value) {
        cell.textLabel.text = value;
        cell.detailTextLabel.text = key;
        if (self.isSearching || indexPath.section == 1) {
            
            cell.textLabel.textColor = [UIColor darkTextColor];
            cell.detailTextLabel.textColor = [UIColor colorWithRed:0.0 green:0.48 blue:1.0 alpha:1.0];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        } else {
            cell.textLabel.textColor = [UIColor darkGrayColor];
            cell.detailTextLabel.textColor = [UIColor grayColor];
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.isSearching || indexPath.section == 1) {
        NSString *key;
        NSString *value;
        
        if (self.isSearching) {
            NSArray *keys = self.filteredTranslations.allKeys;
            key = keys[indexPath.row];
            value = self.filteredTranslations[key];
        } else {
            NSArray *keys = self.customTranslations.allKeys;
            key = keys[indexPath.row];
            value = self.customTranslations[key];
        }
        
        [self showEditDialogForKey:key value:value];
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.isSearching || indexPath.section == 1;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSString *key;
        
        if (self.isSearching) {
            NSArray *keys = self.filteredTranslations.allKeys;
            key = keys[indexPath.row];
        } else {
            NSArray *keys = self.customTranslations.allKeys;
            key = keys[indexPath.row];
        }
        
        [self.customTranslations removeObjectForKey:key];
        [self.filteredTranslations removeObjectForKey:key];
        
        [[NSUserDefaults standardUserDefaults] setObject:self.customTranslations forKey:@"CustomTranslations"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        NSMutableDictionary *newDict = [translationDict mutableCopy];
        [newDict removeObjectForKey:key];
        translationDict = [newDict copy];
        
        if (self.isSearching) {
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        } else {
            [tableView reloadData];
        }
        
        [self refreshAppInterface];
    }
}

- (void)showEditDialogForKey:(NSString *)key value:(NSString *)value {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"编辑翻译"
                                                                   message:nil
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.text = key;
        textField.placeholder = @"原文 (英文)";
        textField.enabled = YES;
    }];
    
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.text = value;
        textField.placeholder = @"译文 (中文)";
    }];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        NSString *newValue = alert.textFields[1].text;
        
        if (newValue.length > 0) {
            self.customTranslations[key] = newValue;
            
            [[NSUserDefaults standardUserDefaults] setObject:self.customTranslations forKey:@"CustomTranslations"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            NSMutableDictionary *newDict = [translationDict mutableCopy];
            newDict[key] = newValue;
            translationDict = [newDict copy];
            
            [self.tableView reloadData];
            
            [self refreshAppInterface];
        }
    }]];
    
    UIViewController *topController = [self topViewController];
    [topController presentViewController:alert animated:YES completion:nil];
}

- (void)refreshAppInterface {
    UIWindow *keyWindow = [self findKeyWindow];
    if (keyWindow) {
        refreshLocalizationInView(keyWindow);
    }
}

- (UIWindow *)findKeyWindow {
    UIWindow *keyWindow = nil;
    
    if (@available(iOS 13.0, *)) {
        for (UIScene *scene in [UIApplication sharedApplication].connectedScenes) {
            if (scene.activationState == UISceneActivationStateForegroundActive && 
                [scene isKindOfClass:[UIWindowScene class]]) {
                UIWindowScene *windowScene = (UIWindowScene *)scene;
                for (UIWindow *window in windowScene.windows) {
                    if (window.isKeyWindow) {
                        keyWindow = window;
                        break;
                    }
                }
                if (keyWindow) break;
            }
        }
    }
    
    if (!keyWindow) {
        NSArray *windows = [UIApplication sharedApplication].windows;
        for (UIWindow *window in windows) {
            if (window.windowLevel == UIWindowLevelNormal) {
                keyWindow = window;
                break;
            }
        }
    }
    
    if (!keyWindow) {
        keyWindow = [UIApplication sharedApplication].windows.firstObject;
    }
    
    return keyWindow;
}

- (UIViewController *)topViewController {
    UIWindow *keyWindow = [self findKeyWindow];
    UIViewController *topController = keyWindow.rootViewController;
    
    while (topController.presentedViewController) {
        topController = topController.presentedViewController;
    }
    
    return topController;
}

@end